package com.system.core.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;

/**
 * 验证码工具类
 */
public final class CaptchaUtils {
    public static final int CAPTCHA_HEIGHT = 28;
    public static final int CAPTCHA_WIDTH = 70;
    public static final int CAPTCHA_LENGTH = 5;
    public static final String CAPTCHA_MIME_TYPE = "jpg";
    public static final String KEY_CAPTCHA = "_captcha";

    /**
     * 生成随机字符
     * <p>
     * 主要用于验证码的随机字符，会替换不容易辨析的0 o I 1这4个字符
     * 此方法一般和getRandCaptchaImage方法联用
     */
    public static String getRandString(int length) {
        String val = "";
        Random random = new Random();
        for(int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            if( "char".equalsIgnoreCase(charOrNum) ) {
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char)(random.nextInt(26) + temp);
            } else if( "num".equalsIgnoreCase(charOrNum) ) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        val = val.replace('0', 'Z').replace('O', 'Y').replace('I', 'S').replace('1', 'M');
        return val;
    }
    
    /**
     * 验证验证码
     *
     * @param session Session of Shiro
     */
    public static boolean matchCaptcha(String input, Session session) {
        String origin = (String) session.getAttribute(KEY_CAPTCHA);
//        System.out.println("[验证码]session验证码是："+origin+"，传入验证码是："+input+"-"+hashCaptcha(input));
        if (StringUtils.isEmpty(origin)) {
            return false;
        }
        boolean match = StringUtils.equalsIgnoreCase(origin, hashCaptcha(input));
        session.removeAttribute(KEY_CAPTCHA);
        return match;
    }

    /**
     * 获得给定范围随机颜色
     */
    public static Color getRandColor(Random random, int fc, int bc) {
        if (fc > 255){
            fc = 255;
        }
        if (bc > 255){
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    /**
     * 生成随机验证字符图片
     * <p/>
     * <p>用法如下:</p>
     * String captcha = getRandString(Utils.CAPTCHA_LENGTH);<br>
     * BufferedImage bi = Utils.getRandCaptchaImage(captcha, random);<br>
     * ImageIO.write(bi, Utils.CAPTCHA_MIME_TYPE, response.getOutputStream());<br>
     */
    public static BufferedImage getRandCaptchaImage(String captcha, Random random) {
        BufferedImage bufferedImage = new BufferedImage(CAPTCHA_WIDTH, CAPTCHA_HEIGHT,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();

        graphics2D.setColor(Color.WHITE);
        graphics2D.fillRect(0, 0, CAPTCHA_WIDTH, CAPTCHA_HEIGHT);
        for (int i = 0; i < 10; i++) {
            graphics2D.setColor(getRandColor(random, 150, 250));
            graphics2D.drawLine(random.nextInt(110), random.nextInt(24), 5 + random.nextInt(10),
                    5 + random.nextInt(10));
        }
        Font font = new Font("Arial", Font.ITALIC, 18);
        graphics2D.setFont(font);
        graphics2D.setColor(new Color(60, 141, 188));
        graphics2D.drawString(captcha, 0, 20);
        return bufferedImage;
    }

    public static String hashCaptcha(String captcha) {
    	String tmp = DigestUtils.md5Hex(captcha.toLowerCase());
//    	System.out.println("[验证码]生成的验证码是："+tmp+"-"+captcha);
        return tmp;
    }
}
